

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.bouncycastle.util.encoders.Hex;

import java.util.Arrays;


public class SM3Util {

    public static final String ENCODING = "UTF-8";

    /**
     * 带秘钥加密
     * src 明文
     * key 秘钥
     **/
    public static String encrypt(String src, String key) throws Exception {
        return Hex.toHexString(getEncryptByKey(src, key));
    }

    /**
     * 根据自定义秘钥进行加密  返回加密后长度为32位的16进制字符串
     * src 源数据
     * key 秘钥
     **/
    public static byte[] getEncryptByKey(String src, String key) throws Exception {
        byte[] srcByte = src.getBytes(ENCODING);
        byte[] keyByte = key.getBytes(ENCODING);
        KeyParameter keyParameter = new KeyParameter(keyByte);
        SM3Digest sm3 = new SM3Digest();
        HMac hMac = new HMac(sm3);
        hMac.init(keyParameter);
        hMac.update(srcByte, 0, srcByte.length);
        byte[] result = new byte[hMac.getMacSize()];
        hMac.doFinal(result, 0);
        return result;
    }

    /**
     * 校验带秘钥加密后的值和数据源是否一致
     **/
    public static boolean verify(String src, String key, String sm3HexStr) throws Exception {
        byte[] sm3HashCode = ByteUtils.fromHexString(sm3HexStr);
        byte[] newHashCode = getEncryptByKey(src, key);
        return Arrays.equals(newHashCode, sm3HashCode);
    }


   
}


